package com.singleton.type6;

/**
 * @author 薛虎
 * @date 2020/12/16 9:12
 * <p>
 * 双重检测,线程安全~效率高
 */
public class SingletonTest06 {

    public static void main(String[] args) {
        System.out.println("双重检测,线程安全~效率高");
        Singleton singleton = Singleton.getInstance();
        Singleton singleton1 = Singleton.getInstance();
        System.out.println(singleton == singleton1); //true
    }

}


//双重检测,线程安全~效率高
class Singleton {

    private static volatile Singleton instance;

    private Singleton() {
    }


    //提供一个静态的公用方法,加入双重检查代码,解决线程安全问题,同时解决懒加载的问题
    //同时保证了效率,推荐使用
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
